package com.github.browep.bat.activities;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import com.github.browep.bat.Constants;
import com.github.browep.bat.R;
import com.github.browep.bat.ScreenService;
import com.google.zxing.client.android.CaptureActivity;
import static com.github.browep.bat.Constants.*;
import static com.github.browep.bat.util.XmlUtil.*;

/**
 * Created by IntelliJ IDEA.
 * User: paul
 * Date: 9/5/11
 * Time: 11:57 PM
 * To change this template use File | Settings | File Templates.
 */
public class PunchCardActivity extends BaseActivity {
    public static final String TAG = PunchCardActivity.class.getSimpleName();
    private ScreenService.Screen screen;
    private int freeCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = new Intent(self,CaptureActivity.class);
        startActivityForResult(intent, R.id.start_qr_scan);

        screen = getScreenService().getScreenById("punch-card");
        String freeCountText = getChildTextContent(screen.getScreenElement(),"free-count");
        freeCount = Integer.parseInt(freeCountText);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == R.id.start_qr_scan && resultCode == R.id.decode_succeeded) {
            String qrText = data.getExtras().getString(QR_TEXT);
            Log.d(TAG, "data:         " + data + "  qrText: " + qrText);

            // decode qr code
            Uri qrUri = Uri.parse(qrText);
            String numStr = qrUri.getQueryParameter("num");
            int num = Integer.valueOf(numStr);

            handleQrScan(num);

        } else if (requestCode == R.id.start_qr_scan && resultCode == 0) {
            // back button pressed?
        } else {
            throw  new IllegalStateException("did not understand return of request code:  " + requestCode + " and result code: " + resultCode);
        }

        finish();
    }

    private void handleQrScan(int num){

        int currentCount = getDao().getInt(CURRENT_COUNT);
        Log.d(TAG,"current count: " + currentCount);
        if(currentCount == -1)
            currentCount = 1;
        else
            currentCount += num;
        Log.d(TAG,"count increased to: " + currentCount);

        getDao().put(CURRENT_COUNT,currentCount);

        sendBroadcast(new Intent(Constants.CARD_PUNCHED_INTENT));

        if(currentCount >= freeCount){
            makeToast("Congratulations!  This coffee is free!");
            getDao().put(CURRENT_COUNT,0);
        }
        else
            makeToast("Success.  You now have " + currentCount + " \"punches\" on your card!");


    }
}
